<?php
class UsersController extends AppController {
	public $uses = array('User');
	
	public function beforeFilter() {
		$this->Auth->allow('*');
		$this->Auth->authenticate = array(
			'Form' => array(
				'fields' => array('username' => 'user_name', 'password' => 'password')
			)
		);
		
		$this->Auth->loginAction = array('controller' => 'users', 'action' => 'login');
		$this->Auth->loginRedirect = array('controller' => 'home', 'action' => 'index');
		$this->Auth->logoutRedirect = array('controller' => 'users', 'action' => 'login');
		$this->Auth->loginError = 'Failed to login';
		$this->Auth->authError = 'Access denied';
	}
	
	public function login() {
		if ($this->Auth->loggedIn()) {
			// Truong hop login roi thi khong cho phep vao trang nay
			$this->redirect(array('controller' => 'home', 'action' => 'index'));
		}
		
		if ($this->request->is('post')) {
			$userLoginInfo = $this->request->data['User'];
			
			$userLoginInfo['password'] = md5($userLoginInfo['password']);
			
			// Tim thong tin trong bang UserMaster
			$userInfo = $this->User->find('first', array(
				'conditions' => array(
					'user_name' => $userLoginInfo['user_name'],
					'password' => $userLoginInfo['password'],
					'delete_flag' => 0
					),
				'contain' => false
				));
				
			if (!empty($userInfo)) {
				if ($this->Auth->login($userInfo['User'])) {
					// Truong hop login thanh cong
					$this->redirect(array('controller' => 'home', 'action' => 'index'));
				} else {
					// Truong hop login that bai
					$this->Session->setFlash('Login failed !!!');
				}
			} else {
				$this->Session->setFlash('Login failed !!!');
			}			
		}
		
		$this->set('title_for_content', 'Login');
	}
	
	public function logout() {
    	$this->Auth->logout();
    	$this->Session->destroy();
    	$this->redirect(array('controller' => 'users', 'action' => 'login'));
    }
}